//index.js
const app = getApp()
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    queryResult: '',
    activeIndex: 1,
    sliderOffset: 0,
    sliderLeft: 0,
    requestResult: '',
    inputShowed: false,
    inputVal: ""
    },

  onLoad: function (options) {
    this.onGetOpenid();
    var that = this;

    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              console.info("用户信息为：" + JSON.stringify(res.userInfo, null, 2));
              app.globalData.nickName = res.userInfo.nickName
              app.globalData.avatarUrl = res.userInfo.avatarUrl
              app.globalData.hignavatarUrl = app.globalData.avatarUrl.replace(/132/g, '0')
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                nickName: res.userInfo.nickName,
                userInfo: res.userInfo
                })
                this.onQuery();
            }
          })
        } else{
          that.setData({
            orglistdata: ''
          })
        }
      }
    })
  },

  QryPlayDetail: function (e) {
    console.log("列表跳转详情页参数：" + e.currentTarget.dataset.id)
    console.log("列表跳转详情页参数中_id值为：" + e.currentTarget.dataset.id._id)
    wx.navigateTo({
      url: '../playdetail/playdetail?id=' + e.currentTarget.dataset.id._id,
    })
  },

  /**
   * 消息订阅
   */
  ClickMessageSend: function (e) {
    
    if (app.globalData.nickName == null) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }

    console.info("消息模板调用ing.......");
    wx.requestSubscribeMessage({
      tmplIds: ['oCYqcR_nT5B4qZs3MuaylO4SqsdkErnSTMvYyee8K1g'],
      success(res) {
        console.info("消息模板调用结束.......");
        console.log("itemSettings:" + JSON.stringify(res, null, 2));
        var itemSettings = JSON.stringify(res, null, 2);
        var userselect = itemSettings.search("reject") != -1;
        console.info("用户选择为：" + userselect);
        if (itemSettings.search("reject") != -1){
            return;
        }

        var nickName = app.globalData.nickName;
        const db = wx.cloud.database()
        db.collection('CLOCKTASK').add({
            data: {
              nickName: nickName
            },
            success: res => {
              wx.reLaunch({
                url: '../msg/msg_success',
              })
              console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
            },
            fail: err => {
              console.error('[数据库] [新增记录] 失败：', err)
            }
          })
      },
      fail: err => {
        console.info("消息模板调用失败......." + err.errMsg + "---" + err.errCode);
      }
    })
  },

  /**
   * 进入打卡页面
   */
  onCheckAuth: function (e) {
    //授权验证
    if (app.globalData.nickName == null) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }

    wx.navigateTo({
      url: '../epidemicadd/epidemicadd',
    })
  },

  onQuery: function (page) {
    wx.showLoading({
      title: '群组查询中',
    })

    var that = this;
    const db = wx.cloud.database();
    
    if (app.globalData.openid == null){
      that.setData({
        orglistdata: ''
      })
      wx.hideLoading()
    }else{
      db.collection('USERORG').where({
        _openid: app.globalData.openid,
        applystatus:'1'
      }).orderBy('addtime', 'desc').get({
        success: res => {
          that.data.queryResult = res.data;
          this.setData({
            orglistdata: that.data.queryResult
          })
          wx.hideLoading()
          console.log('[数据库] [查询记录] 成功: ', res)
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('[数据库] [查询记录] 失败：', err)
        }
      })
    }
  },

  QryOrgDetail: function (e) {
    console.log("列表跳转详情页参数中_id值为：" + e.currentTarget.dataset.id._id)
    var userorgdata = JSON.stringify(e.currentTarget.dataset.id.orgdata)
    console.log("列表跳转详情页参数:" + userorgdata);
    wx.navigateTo({
      url: '../userorgdetail/userorgdetail?userorgdata=' + userorgdata + '&orgid=' + userorgdata._id,
    })
  },

  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },

  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },

  /**
   * 分享给好友
   */
  onShareAppMessage: function () {
    if (app.globalData.nickName == null) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }

    console.log('分享者openid=' + app.globalData.openid)
    return {
      title: app.globalData.nickName +"邀请您一起健康打卡14天",
      imageUrl: "https://6765-geekclub-release-1300915894.tcb.qcloud.la/wuhanjiayou007.jpg",
      path: "/pages/index/index"
    }
  },


  /**
   * 分页处理函数
   */
  onReachBottom: function () {
    var that = this;
    var temp = [];
    // 获取后面十条
    if (this.data.queryResult.length < this.data.totalCount) {
      try {
        const db = wx.cloud.database();
        db.collection('HJACTIVITIES')
          .skip(5)
          .limit(5) // 限制返回数量为 5 条
          .orderBy('date', 'desc') // 排序
          .get({
            success: function (res) {
              // res.data 是包含以上定义的两条记录的数组
              if (res.data.length > 0) {
                for (var i = 0; i < res.data.length; i++) {
                  var tempTopic = res.data[i];
                  console.log(tempTopic);
                  temp.push(tempTopic);
                }
                var totalactivies = {};
                totalactivies = that.data.queryResult.concat(temp);
                that.setData({
                  queryResult: totalactivies,
                })
              } else {
                //wx.showToast({
                //  title: '没有更多数据了',
                //})
              }
            },
            fail: function (event) {
              console.log("======" + event);
            }
          })
      } catch (e) {
        console.error(e);
      }
    } else {
      //wx.showToast({
      //  title: '没有更多数据了',
      //})
    }
  },

  onGetUserInfo: function (e) {
    let that = this;
    // 获取用户信息
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          console.log("已授权=====")
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log("获取用户信息成功", res)
              that.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
              wx.reLaunch({
                url: 'index',
              })
            },
            fail(res) {
              console.log("获取用户信息失败", res)
            }
          })
        } else {
          console.log("未授权=====")
        }
      }
    })
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        var _openid = res.result.openid
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
})
